package com.hdq.websocket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {


    private static Map<String, Session> sessionMap =new HashMap(); // 存放会话对象
    private static Map<String, String> clientRequests = new HashMap<>(); // 存储客户端的请求数据
   private static final ObjectMapper objectMapper=new ObjectMapper();

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println("客户端" + sid +"建立连接");
        sessionMap.put(sid,session);
    }


    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) throws JsonProcessingException {
        System.out.println("收到"+sid+"的消息：" + message);
        JsonNode jsonNode=objectMapper.readTree(message);
        clientRequests.put(sid,jsonNode.toString());
    }

    @OnClose
    public void onClose(@PathParam("sid") String sid){
        System.out.println("连接断开："+ sid);
        sessionMap.remove(sid);
    }

    public void sendToAllClient(String message) {
        for (String key : sessionMap.keySet()) {
            Session session = sessionMap.get(key);
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 定时任务中调用的查询方法
    public String processClientRequest(String sid) {
        String requestData = clientRequests.get(sid);
        if (requestData == null) {
            return null;
        }
        return requestData;
    }
}
